package services

import (
	"context"
	"my-gin-tiktok/app/models"
	"my-gin-tiktok/global"
)

type commentService struct{}

var CommentService = new(commentService)

// CreateComment 新增评论
func (s *commentService) CreateComment(ctx context.Context, userID int64, videoID int64, contents string) error {
	comment := models.Comment{UserID: userID, VideoID: videoID, Contents: contents}
	return global.App.DB.WithContext(ctx).Create(&comment).Error
}

// DeleteComment 删除评论
func (s *commentService) DeleteComment(ctx context.Context, userID int64, videoID int64) error {
	return global.App.DB.WithContext(ctx).Where("user_id = ? and video_id = ?", userID, videoID).Delete(&models.Comment{}).Error
}

// GetUserComments 获取用户评论列表
func (s *commentService) GetUserComments(ctx context.Context, userID int64, page int64, size int64) ([]*models.Comment, error) {
	commentList := make([]*models.Comment, size)
	err := global.App.DB.WithContext(ctx).Where("video_id = ?", userID).Find(&commentList).Error
	if err != nil {
		return nil, err
	}
	return commentList, nil
}

// GetVideoComments 获取视频评论列表
func (s *commentService) GetVideoComments(ctx context.Context, videoID int64, page int64, size int64) ([]*models.Comment, error) {
	commentList := make([]*models.Comment, size)
	err := global.App.DB.WithContext(ctx).Where("video_id = ?", videoID).Find(&commentList).Error
	if err != nil {
		return nil, err
	}
	return commentList, nil
}

// GetUserCounts 批量获取用户评论总量
func (s *commentService) GetUserCounts(ctx context.Context, userIDs []int64) ([]int64, error) {
	countMap := make(map[int64]int64, len(userIDs))
	err := global.App.DB.WithContext(ctx).Exec("select video_id, count(video_id) from video group by video_id").Find(&countMap).Error
	if err != nil {
		return nil, err
	}

	countList := make([]int64, 0, len(countMap))
	for i, v := range userIDs {
		countList[i] = countMap[v]
	}
	return countList, nil
}

// GetVideoCounts 批量获取视频评论总量
func (s *commentService) GetVideoCounts(ctx context.Context, videoIDs []int64) ([]int64, error) {
	countMap := make(map[int64]int64, len(videoIDs))
	err := global.App.DB.WithContext(ctx).Exec("select video_id, count(video_id) from video group by video_id").Find(&countMap).Error
	if err != nil {
		return nil, err
	}

	countList := make([]int64, 0, len(countMap))
	for i, v := range videoIDs {
		countList[i] = countMap[v]
	}
	return countList, nil
}
